Imports BusinessLayer
Imports EntityLayer
Imports System.Data


Partial Class ProductoProveedor
    Inherits System.Web.UI.Page

    Dim myDt As DataTable
#Region " Crear - Llenar Datatable "

    Private Function CreateDataTable() As DataTable
        Dim myDataTable As DataTable = New DataTable()

        Dim myDataColumn As DataColumn

        myDataColumn = New DataColumn()
        myDataColumn.DataType = Type.GetType("System.Int32")
        myDataColumn.ColumnName = "Codigo"
        myDataTable.Columns.Add(myDataColumn)

        myDataColumn = New DataColumn()
        myDataColumn.DataType = Type.GetType("System.String")
        myDataColumn.ColumnName = "Producto"
        myDataTable.Columns.Add(myDataColumn)

        Return myDataTable
    End Function

    Private Sub AddDataToTable(ByVal intCodigo As Integer, ByVal strProducto As String, ByVal myTable As DataTable)
        Dim row As DataRow

        row = myTable.NewRow()

        row("Codigo") = intCodigo
        row("Producto") = strProducto

        myTable.Rows.Add(row)
    End Sub

#End Region

    Protected Sub btnAgregarProducto_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        mpeProducto.Show()
        txtBusqueda.Text = String.Empty
        dgListaProducto.DataSource = ProductoBL.ListarProductos
        dgListaProducto.DataBind()
    End Sub


    Protected Sub dgListaProducto_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Try
            With ProductoBL.ListarProductos(txtBusqueda.Text).Item(dgListaProducto.SelectedIndex)
                'verificamos si el producto ya fue ingresado
                Dim dtcopy As DataTable = CType(Session("myDatatable"), DataTable)
                Dim producto As String = ""
                producto = .Codigo
                Dim filtro As String = "codigo = " + producto
                For Each row1 As DataRow In dtcopy.Select(filtro)
                    If (producto = row1("codigo").ToString) Then
                        ScriptManager.RegisterStartupScript(Me.pnlProducto, Me.GetType, "Script", MessageBox("Producto ya fue agregado"), True)
                        mpeProducto.Show()
                        Return
                    End If
                Next
                'si aun no esta lo insertamos
                AddDataToTable(.Codigo.ToString(), .Nombre.ToString, CType(Session("myDatatable"), DataTable))
                Call MostrarProductoSeleccionado()
            End With
        Catch ex As Exception

        End Try
      End Sub

    Private Sub MostrarProductoSeleccionado()
        dgDatos.DataSource = CType(Session("myDatatable"), DataTable).DefaultView
        dgDatos.DataBind()
    End Sub

    Private Sub ListarProveedor()
        ddlProveedor.DataSource = ProveedorBL.ListarTodo()
        ddlProveedor.DataTextField = "RazonSocial"
        ddlProveedor.DataValueField = "CodigoPro"
        ddlProveedor.DataBind()

    End Sub

    Private Sub Limpiar()
        lblTitulo.Text = "REGISTRO DE PRODUCTO CON PROVEEDOR"
        hfAccion.Value = "ADD"
        txtDireccion.Text = String.Empty
        txtRubro.Text = String.Empty
        txtcontacto.Text = String.Empty
        txtTelefono.Text = String.Empty
        txtWeb.Text = String.Empty
        txtEmail.Text = String.Empty
        txtRUC.Text = String.Empty

        myDt = New DataTable()
        myDt = CreateDataTable()
        Session("myDatatable") = myDt

        dgDatos.DataSource = Nothing
        dgDatos.DataBind()
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then

            ListarProveedor()
            Dim strCodigo As String
            strCodigo = Request.QueryString("strCodigo")

            If strCodigo = Nothing Then
                hfAccion.Value = "ADD"
                lblTitulo.Text = "REGISTRO DE PRODUCTO CON PROVEEDOR"

                myDt = New DataTable()
                myDt = CreateDataTable()
                Session("myDatatable") = myDt

                dgDatos.DataSource = (CType(Session("myDatatable"), DataTable)).DefaultView
                dgDatos.DataBind()
            Else
                hfAccion.Value = "UPD"
                lblTitulo.Text = "MANTENIMIENTO DE PRODUCTO CON PROVEEDOR"
                ddlProveedor.SelectedValue = strCodigo
                LlenarProveedor()
            
                Session("myDatatable") = ProductoProveedorBL.ListarxCodigo(ddlProveedor.SelectedValue).Tables(0)

                dgDatos.DataSource = CType(Session("myDatatable"), DataTable).DefaultView
                dgDatos.DataBind()

            End If
        End If
    End Sub

    Protected Sub chkSelect_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim cb As CheckBox = DirectCast(sender, CheckBox)
        Dim row As GridViewRow = DirectCast(cb.NamingContainer, GridViewRow)

    End Sub

    Protected Sub btnCancelar_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Response.Redirect("ListaProductoProveedor.aspx")
    End Sub


    Protected Sub btnGrabar_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        'Validacion de datos
        '..........................................................
        If (ddlProveedor.SelectedValue = "") Then
            ScriptManager.RegisterStartupScript(Me.PanelMantenimiento, Me.GetType, "Script", MessageBox("Seleccione un proveedor"), True)
            ScriptManager.GetCurrent(Me.Page).SetFocus(ddlProveedor)
            Return
        End If
        '................
        '...............................
        Dim intexisteF As Integer = 0
        For Each row As GridViewRow In dgDatos.Rows
            Dim cb As CheckBox = row.FindControl("chkSelect")
            If cb IsNot Nothing AndAlso cb.Checked Then
                intexisteF = 1
                Exit For
            End If
        Next
        If intexisteF = 0 Then
            ScriptManager.RegisterStartupScript(Me.PanelMantenimiento, Me.GetType, "Script", MessageBox("Debe seleccionar al menos un producto"), True)
            Return
        End If
        '..............................
        If hfAccion.Value = "ADD" Then

            Try
                Dim intexisteFilas As Integer = 0
                For Each row As GridViewRow In dgDatos.Rows

                    Dim cb As CheckBox = row.FindControl("chkSelect")
                    If cb IsNot Nothing AndAlso cb.Checked Then
                        intexisteFilas = 1
                        Exit For
                    End If
                Next

                If intexisteFilas = 1 Then

                    For Each row As GridViewRow In dgDatos.Rows

                        Dim cb As CheckBox = row.FindControl("chkSelect")
                        If cb IsNot Nothing AndAlso cb.Checked Then

                            Dim OBED As New ProductoProveedorBE
                            With OBED
                                .CodigoProducto = row.Cells(1).Text
                                .Descripcion = row.Cells(2).Text
                                .Codigo = ddlProveedor.SelectedValue
                            End With
                            ProductoProveedorBL.Insertar(OBED)
                        End If
                    Next
                End If
                Limpiar()
                ScriptManager.RegisterStartupScript(Me.PanelMantenimiento, Me.GetType, "Script", MessageBox2("Se guardo satisfactoriamente el registro", "ListaProductoProveedor.aspx"), True)

            Catch ex As Exception

            End Try

        ElseIf hfAccion.Value = "UPD" Then
            Try
                Dim intexisteFilas As Integer = 0
                For Each row As GridViewRow In dgDatos.Rows

                    Dim cb As CheckBox = row.FindControl("chkSelect")
                    If cb IsNot Nothing AndAlso cb.Checked Then
                        intexisteFilas = 1
                        Exit For
                    End If
                Next
                If intexisteFilas = 1 Then

                    ProductoProveedorBL.Eliminar(ddlProveedor.SelectedValue)
                    For Each row As GridViewRow In dgDatos.Rows

                        Dim cb As CheckBox = row.FindControl("chkSelect")
                        If cb IsNot Nothing AndAlso cb.Checked Then

                            Dim OBED As New ProductoProveedorBE
                            With OBED
                                .CodigoProducto = row.Cells(1).Text
                                .Descripcion = row.Cells(2).Text
                                .Codigo = ddlProveedor.SelectedValue
                            End With
                            ProductoProveedorBL.Insertar(OBED)
                        End If
                    Next
                End If
                Limpiar()
                ScriptManager.RegisterStartupScript(Me.PanelMantenimiento, Me.GetType, "Script", MessageBox2("Se actualizo satisfactoriamente el registro", "ListaProductoProveedor.aspx"), True)

            Catch ex As Exception

            End Try

        End If

    End Sub

    Private Function MessageBox(ByVal var_mensaje As String) As String
        Return "window.alert('" + var_mensaje + "');"
    End Function

    Private Function MessageBox2(ByVal var_mensaje As String, ByVal var_pagina As String) As String
        Return "window.alert('" + var_mensaje + "');window.location=' " + var_pagina + "';"
    End Function

    Protected Sub btnCerrar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCerrar.Click
        Try
            mpeProducto.Hide()
        Catch ex As Exception

        End Try

    End Sub

    Protected Sub ddlProveedor_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        LlenarProveedor()
    End Sub

    Private Sub LlenarProveedor()
        Dim dt As DataTable
        dt = ProveedorBL.ListarxCodigo(ddlProveedor.SelectedValue).Tables(0)

        txtDireccion.Text = dt.Rows(0)(2).ToString
        txtRubro.Text = dt.Rows(0)(3).ToString
        txtcontacto.Text = dt.Rows(0)(4).ToString
        txtTelefono.Text = dt.Rows(0)(5).ToString
        txtEmail.Text = dt.Rows(0)(6).ToString
        txtWeb.Text = dt.Rows(0)(7).ToString
        txtRUC.Text = dt.Rows(0)(8).ToString

    End Sub


    Protected Sub btnBusqueda_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
        mpeProducto.Show()
        dgListaProducto.DataSource = ProductoBL.ListarProductos(txtBusqueda.Text)
        dgListaProducto.DataBind()
    End Sub
End Class
